/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

/**
 *
 * @author Sujen
 */
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Lid;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.SessionManager;
import security.ActivationKey;
import util.SendMail;
import util.ValidateMail;

public class RegisterController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession sessie = request.getSession(); 
        
        Lid newLid = new Lid();
        sessie.setAttribute("newLid", newLid);
        
        System.out.println("Hop naar register");
            
        String address = "register.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String address;

        String fname = new String();
        String tussenvoegsel = new String();
        String lname = new String();
        String username = new String();
        String password = new String();
        String state = new String();
        String huisnummer = new String();
        String postalcode = new String();
        String emailAdres = new String();
        String usernameTest;
        String dname;
        boolean validOrInvalid = true;
        Date nu = new Date();
        Date geboortedatum = new Date();
        DateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");

        HttpSession sessie = request.getSession();

        Lid lid = new Lid();

        Lid newLid;
        if (sessie.getAttribute("newLid") == null) {

            newLid = new Lid();
        } else {
            newLid = (Lid) sessie.getAttribute("newLid");
        }

        Session session = null;
        session = SessionManager.openSession();
        Transaction tx = session.beginTransaction();

        if (request.getParameter("fname") != null && !request.getParameter("fname").isEmpty()) {
            fname = request.getParameter("fname");
            newLid.setLidVnaam(fname);
        } else {
            request.setAttribute("naam", "Naam is leeg");
            validOrInvalid = false;
        }

        if (request.getParameter("lname") != null && !request.getParameter("lname").isEmpty()) {
            lname = request.getParameter("lname");
            newLid.setLidAnaam(lname);
        } else {
            request.setAttribute("name", "Achternaam is leeg");
            validOrInvalid = false;
        }

        if (request.getParameter("geboortedatum") != null && !request.getParameter("geboortedatum").isEmpty()) {
            try {
                geboortedatum = dateformat.parse(request.getParameter("geboortedatum"));
                newLid.setLidGeboortedatum(geboortedatum);
            } catch (ParseException ex) {
                Logger.getLogger(RitToevoegenController.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("geboortedatum", "Datumformat is onjuist");
                validOrInvalid = false;
            }
        } else {
            request.setAttribute("geboortedatum", "Geboortedatum is leeg");
            validOrInvalid = false;
        }

        if ((request.getParameter("username") != null && !request.getParameter("username").isEmpty())) {
            usernameTest = request.getParameter("username");
            Query q = session.createQuery("from Lid as lid where lid.lidLogin = '" + usernameTest + "'");
            lid = (Lid) q.uniqueResult();
            if (lid != null) {
                request.setAttribute("user", "Username is incorrect");
                validOrInvalid = false;
            } else {
                username = request.getParameter("username");
                newLid.setLidLogin(username);
            }
        } else {
            request.setAttribute("user", "Username is incorrect");
            validOrInvalid = false;
        }
        if (request.getParameter("password") != null && !request.getParameter("password").isEmpty()) {
            password = request.getParameter("password");
        } else {
            request.setAttribute("word", "Wachtwoord is incorrect");
            validOrInvalid = false;
        }

        if (!request.getParameter("state").equals("")) {
            state = request.getParameter("state");
            newLid.setLidProvincie(state);
        } else {
            request.setAttribute("staat", "Provincie is leeg");
            validOrInvalid = false;
        }

        if (request.getParameter("emailAdres") != null && !request.getParameter("emailAdres").isEmpty() && ValidateMail.isEmail(request.getParameter("emailAdres"))) {
            emailAdres = request.getParameter("emailAdres");
            newLid.setLidEmail(emailAdres);
        } else {
            request.setAttribute("mail", "E-mail is incorrect");
            validOrInvalid = false;
        }

        if (request.getParameter("postalcode") != null && !request.getParameter("postalcode").isEmpty()) {
            postalcode = request.getParameter("postalcode");
            newLid.setLidPostcode(postalcode);
        } else {
            request.setAttribute("post", "Postcode is leeg");
            validOrInvalid = false;
        }

        if (request.getParameter("huisnummer") != null && !request.getParameter("huisnummer").isEmpty()) {
            huisnummer = request.getParameter("huisnummer");
            newLid.setLidHuisnummer(huisnummer);
        } else {
            request.setAttribute("huis", "Huisnummer is leeg");
            validOrInvalid = false;
        }

        tussenvoegsel = request.getParameter("insertion");
        newLid.setLidTussenvoegsel(tussenvoegsel);

        if (validOrInvalid != true) {
            // er is iets niet goed ingevult, even terug naar het formulier
            System.out.println("Er is iets niet goed ingevult -> terug naar register.jsp");
            address = "/register.jsp";
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        } else {
            // Alles is oké, tijd voor actie
            if (tussenvoegsel.isEmpty() && request.getParameter("insertion") == null || tussenvoegsel.equals("")) {
                dname = fname.concat(" ").concat(lname);
            } else {
                dname = fname.concat(" ").concat(tussenvoegsel).concat(" ").concat(lname);
            }

            newLid.setLidDisplaynaam(dname);
            newLid.setLidPassword(password);

            newLid.setLidRegistered(nu);
            newLid.setLidActivationkey(ActivationKey.generateActivationKey());
            System.out.println(newLid.getLidActivationkey());
            newLid.setRolId(2);
            newLid.setLidActivated(false);

            session.save(newLid);
            tx.commit();
            session.close();

            //constructie van de activatie url
            String activationUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/Activeren?key=" + newLid.getLidActivationkey();
            try {
                SendMail.send(newLid.getLidEmail(), "Activeer uw Dryves account", activationUrl);
            } catch (AddressException ex) {
                Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MessagingException ex) {
                Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Hop naar MijnBeheer_LedenLijst");

            address = "/login.jsp";
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);

        }
    }
}
